package com.fary.web.context;

import com.fary.context.ApplicationContextInitializer;
import com.fary.web.WebApplicationInitializer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

public abstract class AbstractContextLoaderInitializer implements WebApplicationInitializer {

	/** Logger available to subclasses. */
	protected final Log logger = LogFactory.getLog(getClass());


	/**
	 * 注册ContextLoaderListener
	 */
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		registerContextLoaderListener(servletContext);
	}

	protected void registerContextLoaderListener(ServletContext servletContext) {
		// 创建父容器
		WebApplicationContext rootAppContext = createRootApplicationContext();
		if (rootAppContext != null) {
			ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
			// 通常用于需要对应用程序上下文进行编程初始化的web应用程序中。例如，根据上下文环境注册属性源或激活配置文件等。
			listener.setContextInitializers(getRootApplicationContextInitializers());
			// 添加事件ContextLoaderListener
			servletContext.addListener(listener);
		} else {
			logger.debug("No ContextLoaderListener registered, as " + "createRootApplicationContext() did not return an application context");
		}
	}

	protected abstract WebApplicationContext createRootApplicationContext();

	protected ApplicationContextInitializer<?>[] getRootApplicationContextInitializers() {
		return null;
	}

}